import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../widgets/platform/adaptive_card.dart';
import '../../../../core/platform/platform_detector.dart';

/// 系统监控页面
class MonitoringPage extends ConsumerStatefulWidget {
  const MonitoringPage({super.key});

  @override
  ConsumerState<MonitoringPage> createState() => _MonitoringPageState();
}

class _MonitoringPageState extends ConsumerState<MonitoringPage> {
  @override
  void initState() {
    super.initState();
    // 初始化时加载监控数据
    _loadMonitoringData();
  }

  void _loadMonitoringData() {
    // TODO: 实现加载监控数据的逻辑
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            // 系统概览卡片
            _buildSystemOverview(),
            const SizedBox(height: 16),

            // 性能指标
            _buildPerformanceMetrics(),
            const SizedBox(height: 16),

            // 用户活动统计
            _buildUserActivityStats(),
            const SizedBox(height: 16),

            // 项目统计
            _buildProjectStats(),
            const SizedBox(height: 16),

            // 系统资源使用情况
            _buildResourceUsage(),
          ],
        ),
      ),
    );
  }

  Widget _buildSystemOverview() {
    return AdaptiveCard(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '系统概览',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 16),
          LayoutBuilder(
            builder: (context, constraints) {
              // 桌面平台使用网格布局
              if (PlatformDetector.isDesktop() || PlatformDetector.isWeb()) {
                return _buildDesktopOverviewGrid();
              } else {
                // 移动平台使用列表布局
                return _buildMobileOverviewList();
              }
            },
          ),
        ],
      ),
    );
  }

  Widget _buildDesktopOverviewGrid() {
    return GridView.count(
      crossAxisCount: 4,
      crossAxisSpacing: 16,
      mainAxisSpacing: 16,
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      children: [
        _buildStatCard('用户总数', '24', Icons.people, Colors.blue),
        _buildStatCard('项目总数', '12', Icons.folder, Colors.green),
        _buildStatCard('待办任务', '156', Icons.assignment, Colors.orange),
        _buildStatCard('在线用户', '8', Icons.online_prediction, Colors.purple),
      ],
    );
  }

  Widget _buildMobileOverviewList() {
    return Column(
      children: [
        _buildStatRow('用户总数', '24', Icons.people, Colors.blue),
        _buildStatRow('项目总数', '12', Icons.folder, Colors.green),
        _buildStatRow('待办任务', '156', Icons.assignment, Colors.orange),
        _buildStatRow('在线用户', '8', Icons.online_prediction, Colors.purple),
      ],
    );
  }

  Widget _buildStatCard(
      String title, String value, IconData icon, Color color) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: color.withValues(alpha: 0.1),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: color.withValues(alpha: 0.3)),
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(icon, size: 32, color: color),
          const SizedBox(height: 8),
          SelectableText(
            value,
            style: TextStyle(
              fontSize: 24,
              fontWeight: FontWeight.bold,
              color: color,
            ),
          ),
          SelectableText(
            title,
            style: TextStyle(
              color: color,
              fontSize: 14,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildStatRow(String title, String value, IconData icon, Color color) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8.0),
      child: Row(
        children: [
          Container(
            padding: const EdgeInsets.all(8),
            decoration: BoxDecoration(
              color: color.withValues(alpha: 0.1),
              borderRadius: BorderRadius.circular(8),
            ),
            child: Icon(icon, color: color),
          ),
          const SizedBox(width: 12),
          Expanded(
            child: SelectableText(
              title,
              style: const TextStyle(fontSize: 16),
            ),
          ),
          SelectableText(
            value,
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
              color: color,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildPerformanceMetrics() {
    return AdaptiveCard(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '性能指标',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 16),
          LayoutBuilder(
            builder: (context, constraints) {
              // 桌面平台显示图表
              if (PlatformDetector.isDesktop() || PlatformDetector.isWeb()) {
                return _buildDesktopPerformanceCharts();
              } else {
                // 移动平台显示简化数据
                return _buildMobilePerformanceData();
              }
            },
          ),
        ],
      ),
    );
  }

  Widget _buildDesktopPerformanceCharts() {
    return Column(
      children: [
        // 响应时间图表
        _buildChartCard('API响应时间 (ms)', [
          {'time': '00:00', 'value': 45},
          {'time': '04:00', 'value': 38},
          {'time': '08:00', 'value': 52},
          {'time': '12:00', 'value': 41},
          {'time': '16:00', 'value': 67},
          {'time': '20:00', 'value': 58},
        ]),
        const SizedBox(height: 16),
        // 吞吐量图表
        _buildChartCard('请求吞吐量 (req/s)', [
          {'time': '00:00', 'value': 12},
          {'time': '04:00', 'value': 8},
          {'time': '08:00', 'value': 25},
          {'time': '12:00', 'value': 32},
          {'time': '16:00', 'value': 28},
          {'time': '20:00', 'value': 18},
        ]),
      ],
    );
  }

  Widget _buildMobilePerformanceData() {
    return Column(
      children: [
        _buildSimpleMetric('平均响应时间', '48ms', Icons.speed),
        _buildSimpleMetric('最大响应时间', '126ms', Icons.speed),
        _buildSimpleMetric('每秒请求数', '22 req/s', Icons.sync),
        _buildSimpleMetric('错误率', '0.2%', Icons.error),
      ],
    );
  }

  Widget _buildChartCard(String title, List<Map<String, dynamic>> data) {
    return Container(
      height: 200,
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.grey[50],
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: Colors.grey[300]!),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SelectableText(
            title,
            style: const TextStyle(
              fontWeight: FontWeight.bold,
              fontSize: 16,
            ),
          ),
          const SizedBox(height: 8),
          Expanded(
            child: CustomPaint(
              painter: LineChartPainter(data),
              child: const SizedBox.expand(),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildSimpleMetric(String label, String value, IconData icon) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8.0),
      child: Row(
        children: [
          Icon(icon, size: 20, color: Colors.blue),
          const SizedBox(width: 12),
          SelectableText(
            label,
            style: const TextStyle(fontSize: 16),
          ),
          const Spacer(),
          SelectableText(
            value,
            style: const TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildUserActivityStats() {
    return AdaptiveCard(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '用户活动统计',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 16),
          // 活跃用户图表
          _buildActivityChart(),
        ],
      ),
    );
  }

  Widget _buildActivityChart() {
    final activityData = [
      {'day': '周一', 'active': 12, 'new': 3},
      {'day': '周二', 'active': 15, 'new': 2},
      {'day': '周三', 'active': 18, 'new': 5},
      {'day': '周四', 'active': 14, 'new': 1},
      {'day': '周五', 'active': 22, 'new': 4},
      {'day': '周六', 'active': 8, 'new': 0},
      {'day': '周日', 'active': 6, 'new': 1},
    ];

    return LayoutBuilder(
      builder: (context, constraints) {
        // 桌面平台显示柱状图
        if (PlatformDetector.isDesktop() || PlatformDetector.isWeb()) {
          return Container(
            height: 200,
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: Colors.grey[50],
              borderRadius: BorderRadius.circular(8),
              border: Border.all(color: Colors.grey[300]!),
            ),
            child: CustomPaint(
              painter: BarChartPainter(activityData),
              child: const SizedBox.expand(),
            ),
          );
        } else {
          // 移动平台显示简化数据
          return Column(
            children: activityData.map((data) {
              return Padding(
                padding: const EdgeInsets.symmetric(vertical: 4.0),
                child: Row(
                  children: [
                    SizedBox(
                      width: 40,
                      child: SelectableText(data['day'] as String),
                    ),
                    const SizedBox(width: 8),
                    Expanded(
                      child: LinearProgressIndicator(
                        value: (data['active'] as int) / 25.0,
                        backgroundColor: Colors.grey[300],
                        valueColor:
                            const AlwaysStoppedAnimation<Color>(Colors.blue),
                      ),
                    ),
                    const SizedBox(width: 8),
                    SelectableText('${data['active']}'),
                  ],
                ),
              );
            }).toList(),
          );
        }
      },
    );
  }

  Widget _buildProjectStats() {
    return AdaptiveCard(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '项目统计',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 16),
          _buildProjectStatusChart(),
        ],
      ),
    );
  }

  Widget _buildProjectStatusChart() {
    final statusData = [
      {'status': '进行中', 'count': 5, 'color': Colors.blue},
      {'status': '已完成', 'count': 3, 'color': Colors.green},
      {'status': '计划中', 'count': 2, 'color': Colors.orange},
      {'status': '测试中', 'count': 1, 'color': Colors.purple},
      {'status': '已取消', 'count': 1, 'color': Colors.red},
    ];

    return LayoutBuilder(
      builder: (context, constraints) {
        // 桌面平台显示饼图
        if (PlatformDetector.isDesktop() || PlatformDetector.isWeb()) {
          return Container(
            height: 200,
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: Colors.grey[50],
              borderRadius: BorderRadius.circular(8),
              border: Border.all(color: Colors.grey[300]!),
            ),
            child: CustomPaint(
              painter: PieChartPainter(statusData),
              child: const SizedBox.expand(),
            ),
          );
        } else {
          // 移动平台显示列表
          return Column(
            children: statusData.map((data) {
              return Padding(
                padding: const EdgeInsets.symmetric(vertical: 4.0),
                child: Row(
                  children: [
                    Container(
                      width: 12,
                      height: 12,
                      decoration: BoxDecoration(
                        color: data['color'] as Color,
                        borderRadius: BorderRadius.circular(6),
                      ),
                    ),
                    const SizedBox(width: 8),
                    SelectableText(data['status'] as String),
                    const Spacer(),
                    SelectableText('${data['count']}'),
                  ],
                ),
              );
            }).toList(),
          );
        }
      },
    );
  }

  Widget _buildResourceUsage() {
    return AdaptiveCard(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '系统资源使用情况',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 16),
          _buildResourceUsageList(),
        ],
      ),
    );
  }

  Widget _buildResourceUsageList() {
    final resources = [
      {
        'name': 'CPU使用率',
        'value': 45,
        'unit': '%',
        'color': Colors.blue,
        'status': '正常'
      },
      {
        'name': '内存使用率',
        'value': 68,
        'unit': '%',
        'color': Colors.orange,
        'status': '正常'
      },
      {
        'name': '磁盘使用率',
        'value': 32,
        'unit': '%',
        'color': Colors.green,
        'status': '正常'
      },
      {
        'name': '网络IO',
        'value': 120,
        'unit': 'Mbps',
        'color': Colors.purple,
        'status': '正常'
      },
    ];

    return Column(
      children: resources.map((resource) {
        return Padding(
          padding: const EdgeInsets.symmetric(vertical: 8.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  SelectableText(resource['name'] as String),
                  const Spacer(),
                  SelectableText(
                    '${resource['value']}${resource['unit']}',
                    style: const TextStyle(fontWeight: FontWeight.bold),
                  ),
                  const SizedBox(width: 8),
                  Container(
                    padding:
                        const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                    decoration: BoxDecoration(
                      color: Colors.green[100],
                      borderRadius: BorderRadius.circular(4),
                    ),
                    child: SelectableText(
                      resource['status'] as String,
                      style: const TextStyle(
                        color: Colors.green,
                        fontSize: 12,
                      ),
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 4),
              LinearProgressIndicator(
                value: (resource['value'] as int) / 100.0,
                backgroundColor: Colors.grey[300],
                valueColor:
                    AlwaysStoppedAnimation<Color>(resource['color'] as Color),
              ),
            ],
          ),
        );
      }).toList(),
    );
  }
}

// 简单的折线图绘制器
class LineChartPainter extends CustomPainter {
  final List<Map<String, dynamic>> data;

  LineChartPainter(this.data);

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = Colors.blue
      ..strokeWidth = 2
      ..style = PaintingStyle.stroke;

    final points = <Offset>[];
    final maxValue =
        data.map((d) => d['value'] as int).reduce((a, b) => a > b ? a : b);

    for (int i = 0; i < data.length; i++) {
      final x = (size.width / (data.length - 1)) * i;
      final y =
          size.height - ((data[i]['value'] as int) / maxValue) * size.height;
      points.add(Offset(x, y));
    }

    for (int i = 0; i < points.length - 1; i++) {
      canvas.drawLine(points[i], points[i + 1], paint);
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}

// 简单的柱状图绘制器
class BarChartPainter extends CustomPainter {
  final List<Map<String, dynamic>> data;

  BarChartPainter(this.data);

  @override
  void paint(Canvas canvas, Size size) {
    final activePaint = Paint()..color = Colors.blue;
    final newPaint = Paint()..color = Colors.green;

    final maxValue = data
        .map((d) =>
            (d['active'] as int) > (d['new'] as int) ? d['active'] : d['new'])
        .reduce((a, b) => a > b ? a : b);

    final barWidth = size.width / data.length * 0.6;
    final spacing = size.width / data.length * 0.4;

    for (int i = 0; i < data.length; i++) {
      final x = (size.width / data.length) * i + spacing / 2;
      final activeHeight =
          ((data[i]['active'] as int) / maxValue) * size.height * 0.8;
      final newHeight =
          ((data[i]['new'] as int) / maxValue) * size.height * 0.8;

      // 绘制活跃用户柱
      canvas.drawRect(
        Rect.fromLTWH(
          x,
          size.height - activeHeight,
          barWidth / 2 - 2,
          activeHeight,
        ),
        activePaint,
      );

      // 绘制新增用户柱
      canvas.drawRect(
        Rect.fromLTWH(
          x + barWidth / 2 + 2,
          size.height - newHeight,
          barWidth / 2 - 2,
          newHeight,
        ),
        newPaint,
      );
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}

// 简单的饼图绘制器
class PieChartPainter extends CustomPainter {
  final List<Map<String, dynamic>> data;

  PieChartPainter(this.data);

  @override
  void paint(Canvas canvas, Size size) {
    final center = Offset(size.width / 2, size.height / 2);
    final radius = size.width / 2 * 0.8;

    double startAngle = 0;
    final total = data.map((d) => d['count'] as int).reduce((a, b) => a + b);

    for (int i = 0; i < data.length; i++) {
      final sweepAngle = (data[i]['count'] as int) / total * 360;
      final paint = Paint()
        ..color = data[i]['color'] as Color
        ..style = PaintingStyle.fill;

      canvas.drawArc(
        Rect.fromCircle(center: center, radius: radius),
        startAngle * 0.0174533, // 转换为弧度
        sweepAngle * 0.0174533, // 转换为弧度
        true,
        paint,
      );

      startAngle += sweepAngle;
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
